import { createApp } from "vue";
import ContextMenu from "./components/Menus.vue";

type elementIconType = import("vue").DefineComponent<
  {},
  {},
  {},
  {},
  {},
  import("vue").ComponentOptionsMixin,
  import("vue").ComponentOptionsMixin,
  import("vue").EmitsOptions,
  string,
  import("vue").VNodeProps &
    import("vue").AllowedComponentProps &
    import("vue").ComponentCustomProps,
  Readonly<{} & {} & {}>,
  {}
>; // copy来的

export type MenuItemType<I = string | elementIconType> = {
  label: string;
  icon?:
    | I
    | {
        node: I;
        option?: {
          [key: string]: unknown;
        };
      };
  customIcon?: boolean;
  disabled?: boolean;
  divided?: boolean;
  click?: (...arg: unknown[]) => unknown;
  children?: Array<MenuItemType>;
  tip?: string;
};

type BaseType<T = string | elementIconType> = {
  menus: Array<MenuItemType<T>>;
  menusStyle: {
    [key: string]: unknown;
  };
  menusItemClass?: string;
  minWidth?: number | string;
  maxWidth?: number | string;
  zIndex?: number | string;
};

export type MenuType<T = string | elementIconType> =
  | ({
      event: MouseEvent;
    } & BaseType<T>)
  | {
      position:
        | ({
            x: number;
            y: number;
          } & BaseType<T>)
        | ({
            event?: MouseEvent;
            position?: {
              x: number;
              y: number;
            };
          } & BaseType<T>);
    };

let lastInstance: any = null;

function mouseEvent() {
  if (lastInstance) {
    lastInstance.close();
    lastInstance = null;
  }
  // 三种操作时关闭menu
  document.removeEventListener("contextmenu", mouseEvent);
  document.removeEventListener("click", mouseEvent);
  document.removeEventListener("wheel", mouseEvent);
}

function $menusEvent(menus: any, event: MouseEvent) {
  const temp = menus || {};
  if (lastInstance) {
    lastInstance.close();
    lastInstance = null;
    document.removeEventListener("contextmenu", mouseEvent);
  }
  let instance = createApp(ContextMenu, { event, ...temp });

  lastInstance = instance.mount(document.createElement("div"));
  // instance.mount(document.createElement("div"))
  lastInstance.$unmount = instance.unmount;

  event.preventDefault();

  let timer: any = setTimeout(() => {
    document.addEventListener("contextmenu", mouseEvent);
    document.addEventListener("click", mouseEvent);
    document.addEventListener("wheel", mouseEvent);
    clearTimeout(timer);
    timer = null;
  }, 0);

  return lastInstance;
}

export default $menusEvent;
